<template>
	<view class="container">
		<scroll-view class="scroll" scroll-y="true" :refresher-enabled="false" :refresher-triggered="triggered"
			:refresher-threshold="100" refresher-background="#F9F6F6" @refresherrefresh="onRefresh"
			@scrolltolower="tolower">
			<template v-if="userList.length>0" v-for="item in userList">
				<view class="intro" @click="toChat(item)" :style="{
					borderBottom: `${['system','order'].includes(item.conversationType)?16:1}rpx solid var(--pages-bg-color)`
				}">
					<image class="avatar"
						:src="item.lastMessage.ext[item.conversationId] && item.lastMessage.ext[item.conversationId].avatar"
						mode=""></image>
					<view class="intro-right">
						<view class="intro-top">
							<uni-badge class="uni-badge-left-margin" :text="item.unReadCount" absolute="rightTop"
								:offset="[-2, -2]" size="small" :customStyle="{background: '#6363FF'}">
								<view class="name" v-if="item.lastMessage.ext[item.conversationId]">
									{{item.lastMessage.ext[item.conversationId].username.slice(0,7)}}
									{{item.lastMessage.ext[item.conversationId].username.length>7?'...':''}}
								</view>
							</uni-badge>
							<view class="time" v-if="item.lastMessage.time">
								{{chatTime(item.lastMessage.time)}}
							</view>

						</view>
						<view v-if="item.lastMessage.type=='txt'" class="intro-msg xjs-line-one">
							{{item.lastMessage.msg}}
						</view>
						<view v-if="item.lastMessage.type=='img'" class="intro-msg xjs-line-one">[图片]</view>
						<view v-if="item.lastMessage.type=='video'" class="intro-msg xjs-line-one">[视频]</view>
					</view>
				</view>
			</template>
			<loadMore :status="loadingStatus" />
		</scroll-view>
	</view>
</template>

<script setup lang="ts">
	import { useImStoreToRefs } from '@/store/useImStore'
	import { chatTime } from '@/hooks/useDay'
	import { ref, reactive, onMounted } from 'vue'
	import api from '@/api'
	const userList = ref([])
	const { imServer, messagePoint } = useImStoreToRefs()
	const triggered = ref(false)
	const loadingStatus = ref("loading")

	import { useUserStoreToRefs } from '@/store/useUserStore'
	onMounted(async () => {
		uni.$on("onChatUserList", () => {
			getUserList()
		})
		getUserList()
	})
	const onRefresh = () => {

	}
	const tolower = () => {

	}
	const getUserList = async () => {
		let list = []
		//获取系统和订单消息 拼接到聊天消息的最前面
		let sysResult : any = await systemMessage()
		console.log('systemsystemsystem', sysResult)
		loadingStatus.value = "loading"
		imServer.value.getServerConversations((res) => {
			console.log("消息用户列表组件", res)
			list = sysResult.concat(res.data.conversations)
			if (res.data.cursor) {
				loadingStatus.value = "more"
			} else {
				if (list.length == 0) {
					loadingStatus.value = "empty"
				} else {
					loadingStatus.value = "noMore"
				}
			}
			userList.value = list
			getMessagePoint()
		})
	}
	const systemMessage = () => {
		return new Promise(async (resolve) => {
			const res : any = await api({
				method: 'get',
				url: `/mall/appMessage/getLast`
			})
			let { orderMessage, orderUnReadCount, sysMessage, sysUnReadCount } = res.data
			resolve([{
				conversationId: "order",
				unReadCount: orderUnReadCount,
				conversationType: "order",
				lastMessage: {
					time: orderMessage ? new Date(orderMessage.createTime).getTime() : '',
					ext: {
						"order": {
							avatar: "https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-73.png",
							username: "订单消息",
						}
					},
					msg: orderMessage ? orderMessage.content : '',
					type: 'txt'
				}
			}, {
				conversationId: "system",
				unReadCount: sysUnReadCount,
				conversationType: "system",
				lastMessage: {
					time: sysMessage ? new Date(sysMessage.createTime).getTime() : '',
					ext: {
						"system": {
							avatar: "https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-74.png",
							username: "系统消息",
						}
					},
					msg: sysMessage ? sysMessage.content : '',
					type: 'txt'
				}
			}])
		})

	}
	const toChat = (item) => {
		switch (item.conversationType) {
			case 'order':
			case 'system':
				uni.navigateTo({
					// 消息类型：1-订单消息  2-系统消息
					url: `/pages/setting/message/index?conversationType=${item.conversationType=='order'?1:2}&title=${item.lastMessage.ext[item.conversationId].username}`
				})
				break;
			default:
				let conversationId = item.conversationId;
				let username = item.lastMessage.ext[item.conversationId] && item.lastMessage.ext[item.conversationId].username;
				let avatar = item.lastMessage.ext[item.conversationId] && item.lastMessage.ext[item.conversationId].avatar;
				uni.navigateTo({
					url: `/pages/im/message/index?id=${conversationId.split('_')[1]}&username=${username}&avatar=${avatar}`
				})
				break;
		}

	}
	const getMessagePoint = () => {
		let num = 0
		userList.value.forEach((item) => {
			num += item.unReadCount
		});
		messagePoint.value = num
		// #ifdef APP-PLUS
		plus.runtime.setBadgeNumber(messagePoint.value)
		// #endif
	}
	defineExpose({ getUserList })
</script>

<style lang="scss" scoped>
	.container {
		box-sizing: border-box;
		background-color: #fff;

		.scroll {
			height: calc(100vh - var(--safe-area-bottom) - 100rpx);

			.intro {
				@include flex(center);
				padding: 48rpx 40rpx;
				border-bottom: 1rpx solid #E4E6E6;

				.avatar {
					width: 96rpx;
					height: 96rpx;
					border-radius: 50%;
				}

				.intro-right {
					width: calc(100% - 120rpx);
					margin-left: 24rpx;

					.intro-top {
						@include flex(center, space-between);

						.name {
							font-size: 32rpx;
							font-weight: bold;
						}

						.time {
							flex-shrink: 0;
							color: #7C807F;
							font-size: 26rpx;
							margin-left: 12rpx;
						}
					}

					.intro-msg {
						font-size: 26rpx;
						margin-top: 16rpx;
						width: 480rpx;
					}
				}
			}
		}

	}
</style>